Adding ICPC Live Archive
[andmenj-acm.git] / ICPC Live Archive / 3928 - Ballroom lights / help / gomox.ar-pap-2010-d9b17e5cb110 / tpa / doc / 3nmas1.tex
blob7319ddbbbe6787ad14c78412abb62521466b6386
1 \section{100 - The $3n + 1$ problem}
3 \textbf{Problema:} dados $i$ y $j$, encontrar la longitud m\'axima del ciclo, seg\'un la sucesi\'on de Collatz, para todos los
4 n\'umeros entre $i$ y $j$, donde $i, j$ est\'an en el rango $[1,1\,000\,000)$.
6 \begin{figure}[H]
7 \centering
8 \includegraphics[scale=0.70]{./figuras/collatz_conjecture.png}
9 \end{figure}
11 \subsection{Resoluci\'on}
12 Para resolver este ejercicio se calculan los per\'iodos de todos los n\'umeros entre $i$ y $j$,
13 memorizando en un arreglo los per\'iodos ya calculados, para de esta manera no repetir c\'alculos.
15 Como estructura para memorizar, se utiliza un arreglo de un mill\'on de posiciones.
16 En general, para calcular el per\'iodo de los n\'umeros en $[1,n]$,
17 {\em podr\'ia} ser necesario calcular valores fuera de ese rango. La decisi\'on que tomamos fue no
18 memorizar el per\'iodo de los n\'umeros mayores que $999\,999$.
19 Ensayamos otras implementaciones que usaban un \texttt{map} para
20 memorizar los per\'iodos de todos los valores, pero en la pr\'actica
21 (adem\'as de cambiar la complejidad por usar un diccionario sobre \'arbol binario)
22 esto introduc\'ia un factor constante que lo hac\'ia bastante m\'as lento.
24 Si hubiera muchas b\'usquedas en intervalos grandes, se podr\'ia pensar en usar alguna
25 estructura de datos auxiliar que permitiera determinar r\'apidamente el
26 m\'aximo de un intervalo de un arreglo (como rmq). A modo de prueba, implementamos
27 una versi\'on simple de rmq (en la que una consulta cuesta $O(\sqrt{n})$), pero
28 el algorimo que usaba esa estructura tambi\'en resultaba comparativamente
29 costoso en la pr\'actica.
31 %, porque usando un arreglo esto podr\'ia eventualmente necesitar una gran cantidad de memoria.
32 %%Es por esta razón que podría ocurrir que se repitan calculos, sin embargo creemos que el impacto que tienen esas repeticiones es despreciable.
33 %A la hora de realizar varias b\'usquedas, cada una se beneficia de los c\'a de periodos hechos en las anteriores. No obstante ello, si hay muchas busquedas grandes, todas recorren el rango entero. Esto podría hacerse de modo mas eficiente a fin de reducir el tiempo de las busquedas, sin embargo consideramos que eso escapa al problema.
35 Como observaci\'on adicional, se puede ver que, si $i \leq \lfloor j / 2 \rfloor$, no es
36 necesario buscar el m\'aximo en todo el intervalo $[i,j]$,
37 porque todos los valores menores que $j / 2$ tienen a su doble
38 dentro del intervalo. Por lo cual, dado que $periodo(2x) = periodo(x) + 1$,
39 el valor m\'aximo no se alcanza antes de $\lceil j / 2 \rceil$.
41 \begin{algorithm}[H]
42 \begin{algorithmic}
43 \caption{M\'aximo per\'iodo en un intervalo}
44 \PARAMS{$i,j$: bordes del intervalo donde buscar (se asume $i \leq j$)}
45 \ENSURE{ $maximo$: largo del per\'iodo máximo}
46 \STATE $periodo_1 := 1$
47 \STATE $desde := max(i,\lceil j/2 \rceil)$
48 \STATE $maximo := 0$
49 \FOR{cada $n$ entre $desde$ y $j$}
50 \STATE $maximo := max(maximo, periodo_n)$
51 \ENDFOR
52 %\RETURN $maximo$
53 \end{algorithmic}
54 \end{algorithm}
56 \begin{algorithm}[H]
57 \begin{algorithmic}
58 \caption{Per\'iodo de un n\'umero de acuerdo con la relaci\'on de Collatz}
59 \PARAMS{$i$: n\'umero cuyo per\'iodo interesa conocer}
60 \IF{$periodo_i$ est\'a memorizado}
61 \RETURN valor memorizado
62 \ELSE
63 \STATE $p := periodo_{i'} + 1$ donde $i'$ es el siguiente de $i$ seg\'un la relaci\'on de Collatz
64 \STATE memorizar $periodo_i = p$ si corresponde
65 \RETURN $p$
66 \ENDIF
67 \end{algorithmic}
68 \end{algorithm}
70 Con respecto a la complejidad, si se tiene como entrada el intervalo $[i,j]$ (asumiendo
71 $i \leq j$), se calcula el per\'iodo de a lo sumo $j - i + 1$ números. Ahora bien, $O(j-i) \subseteq O(j)$.
72 En muchos casos, calcular el per\'iodo requiere pocos pasos, porque alcanza con
73 buscar en el arreglo un per\'iodo ya calculado en otro paso; pero esto no ocurre siempre.
74 Sea $P$ el per\'iodo máximo en el intervalo sobre el que se realiza la consulta. Como cota superior
75 para el peor caso, calcular cada per\'iodo requiere $P$ pasos. Por esta raz\'on, la complejidad
76 del algoritmo es $O(P \cdot j)$.
77 Esta cota es bastante pesimista, ya que muy pocas veces se hacen
78 $P$ c\'alculos por número.
80 %En particular, una vez que ya se calcularon todos
81 %los per\'iodos, las posteriores b\'usquedas requieren $O(max(i,j))$, ya que
82 %s\'olo se debe buscar el m\'aximo entre los valores de un arreglo.
83 En particular, si se realizan $n$ consultas, la complejidad, calculada
84 de la manera anterior, ser\'ia $O(P \cdot \sum_{k=1}^{n}{j_k})$,
85 donde $[i_k,j_k]$ es el intervalo de la $k$-\'esima consulta.
86 Pero, dado que acceder a un elemento ya memorizado es $O(1)$, el costo
87 del algoritmo es a lo sumo el de inicializar todo el arreglo una vez
88 m\'as el de buscar el m\'aximo para responder cada consulta, es
89 decir $O(P \cdot j_{\max} + \sum_{k=1}^{n}{j_k})$, donde $j_{\max} = \max_k{j_k}$.
91 En el intervalo $[1,999\,999]$ el valor de $P$ es $525$. Sin embargo, en
92 general, $P$ no es f\'acil de acotar. De hecho, si se pudiera acotar siempre,
93 se habr\'ia resuelto la conjetura de Collatz.
95 \subsection{Implementación}
97 \noindent
98 \ttfamily
99 \shorthandoff{"}\\
100 \hlstd{}\hlline{\ 1\ }\hldir{\#include\ $<$stdio.h$>$}\\
101 \hlline{\ 2\ }\hlstd{}\hldir{\#include\ $<$iostream$>$}\\
102 \hlline{\ 3\ }\hlstd{}\hldir{\#include\ $<$vector$>$}\\
103 \hlline{\ 4\ }\hlstd{}\hlkwa{using\ namespace\ }\hlstd{std}\hlsym{;}\\
104 \hlline{\ 5\ }\hlstd{}\\
105 \hlline{\ 6\ }\hlkwc{typedef\ }\hlstd{}\hlkwb{unsigned\ int\ }\hlstd{uint}\hlsym{;}\\
106 \hlline{\ 7\ }\hlstd{}\hlkwc{typedef\ }\hlstd{}\hlkwb{unsigned\ short\ }\hlstd{ushort}\hlsym{;}\\
107 \hlline{\ 8\ }\hlstd{}\\
108 \hlline{\ 9\ }\hldir{\#define\ Max\textunderscore memo\ 1000001}\\
109 \hlline{10\ }\hlstd{vector}\hlsym{$<$}\hlstd{ushort}\hlsym{$>$\ }\hlstd{}\hlkwd{d}\hlstd{}\hlsym{(}\hlstd{Max\textunderscore memo}\hlsym{,\ }\hlstd{}\hlnum{0}\hlstd{}\hlsym{);}\\
110 \hlline{11\ }\hlstd{}\\
111 \hlline{12\ }\hldir{\#define\ memorizado(x)\ ((x)\ $<$\ Max\textunderscore memo\ \&\&\ d{[}(x){]}\ !=\ 0)}\\
112 \hlline{13\ }\hlstd{}\hldir{\#define\ next(n)\ ((n)\ \%\ 2\ ==\ 0\ ?\ (n)\ /\ 2\ :\ 3\ {*}\ (n)\ +\ 1)}\\
113 \hlline{14\ }\hlstd{\\
114 \hlline{15\ }ushort\ }\hlkwd{periodo}\hlstd{}\hlsym{(}\hlstd{uint\ n}\hlsym{)\ \{}\\
115 \hlline{16\ }\hlstd{\ }\hlkwa{if\ }\hlstd{}\hlsym{(}\hlstd{}\hlkwd{memorizado}\hlstd{}\hlsym{(}\hlstd{n}\hlsym{))\ \{}\\
116 \hlline{17\ }\hlstd{}\hlstd{\ \ }\hlstd{}\hlkwa{return\ }\hlstd{d}\hlsym{{[}}\hlstd{n}\hlsym{{]};}\\
117 \hlline{18\ }\hlstd{\ }\hlsym{\}\ }\hlstd{}\hlkwa{else\ }\hlstd{}\hlsym{\{}\\
118 \hlline{19\ }\hlstd{}\hlstd{\ \ }\hlstd{ushort\ p\ }\hlsym{=\ }\hlstd{}\hlkwd{periodo}\hlstd{}\hlsym{(}\hlstd{}\hlkwd{next}\hlstd{}\hlsym{(}\hlstd{n}\hlsym{))\ +\ }\hlstd{}\hlnum{1}\hlstd{}\hlsym{;}\\
119 \hlline{20\ }\hlstd{}\hlstd{\ \ }\hlstd{}\hlkwa{if\ }\hlstd{}\hlsym{(}\hlstd{n\ }\hlsym{$<$\ }\hlstd{Max\textunderscore memo}\hlsym{)\ \{}\\
120 \hlline{21\ }\hlstd{}\hlstd{\ \ \ }\hlstd{d}\hlsym{{[}}\hlstd{n}\hlsym{{]}\ =\ }\hlstd{p}\hlsym{;}\\
121 \hlline{22\ }\hlstd{}\hlstd{\ \ }\hlstd{}\hlsym{\}}\\
122 \hlline{23\ }\hlstd{}\hlstd{\ \ }\hlstd{}\hlkwa{return\ }\hlstd{p}\hlsym{;}\\
123 \hlline{24\ }\hlstd{\ }\hlsym{\}}\\
124 \hlline{25\ }\hlstd{}\hlsym{\}}\\
125 \hlline{26\ }\hlstd{\\
126 \hlline{27\ }ushort\ }\hlkwd{resolver}\hlstd{}\hlsym{(}\hlstd{uint\ x}\hlsym{,\ }\hlstd{uint\ y}\hlsym{)\{}\\
127 \hlline{28\ }\hlstd{\ ushort\ res\ }\hlsym{=\ }\hlstd{}\hlnum{0}\hlstd{}\hlsym{;}\\
128 \hlline{29\ }\hlstd{\ uint\ i\ }\hlsym{=\ }\hlstd{}\hlkwd{min}\hlstd{}\hlsym{(}\hlstd{x}\hlsym{,}\hlstd{y}\hlsym{);}\\
129 \hlline{30\ }\hlstd{\ uint\ sup\ }\hlsym{=\ }\hlstd{}\hlkwd{max}\hlstd{}\hlsym{(}\hlstd{x}\hlsym{,}\hlstd{y}\hlsym{);}\\
130 \hlline{31\ }\hlstd{\ ushort\ aux}\hlsym{;}\\
131 \hlline{32\ }\hlstd{\ i\ }\hlsym{=\ }\hlstd{}\hlkwd{max}\hlstd{}\hlsym{(}\hlstd{sup}\hlsym{/}\hlstd{}\hlnum{2}\hlstd{}\hlsym{,}\hlstd{i}\hlsym{);}\\
132 \hlline{33\ }\hlstd{\\
133 \hlline{34\ }\ }\hlkwa{while}\hlstd{}\hlsym{(}\hlstd{i\ }\hlsym{$<$=\ }\hlstd{sup}\hlsym{)\{}\\
134 \hlline{35\ }\hlstd{}\hlstd{\ \ }\hlstd{aux\ }\hlsym{=\ }\hlstd{}\hlkwd{periodo}\hlstd{}\hlsym{(}\hlstd{i}\hlsym{);}\\
135 \hlline{36\ }\hlstd{}\hlstd{\ \ }\hlstd{}\hlkwa{if\ }\hlstd{}\hlsym{(}\hlstd{aux\ }\hlsym{$>$\ }\hlstd{res}\hlsym{)\{}\\
136 \hlline{37\ }\hlstd{}\hlstd{\ \ \ }\hlstd{res\ }\hlsym{=\ }\hlstd{aux}\hlsym{;}\\
137 \hlline{38\ }\hlstd{}\hlstd{\ \ }\hlstd{}\hlsym{\}}\\
138 \hlline{39\ }\hlstd{}\hlstd{\ \ }\hlstd{i}\hlsym{++;}\\
139 \hlline{40\ }\hlstd{\ }\hlsym{\}}\\
140 \hlline{41\ }\hlstd{\ }\hlkwa{return\ }\hlstd{res}\hlsym{;}\\
141 \hlline{42\ }\hlstd{}\hlsym{\}}\\
142 \hlline{43\ }\hlstd{}\\
143 \hlline{44\ }\hlkwb{int\ }\hlstd{}\hlkwd{main}\hlstd{}\hlsym{(}\hlstd{}\hlkwb{int\ }\hlstd{argc}\hlsym{,\ }\hlstd{}\hlkwb{char\ }\hlstd{}\hlsym{{*}{*}}\hlstd{argv}\hlsym{)}\\
144 \hlline{45\ }\hlstd{}\hlsym{\{}\\
145 \hlline{46\ }\hlstd{\ uint\ x}\hlsym{,\ }\hlstd{y}\hlsym{;}\\
146 \hlline{47\ }\hlstd{\ d}\hlsym{{[}}\hlstd{}\hlnum{1}\hlstd{}\hlsym{{]}\ =\ }\hlstd{}\hlnum{1}\hlstd{}\hlsym{;}\\
147 \hlline{48\ }\hlstd{\ }\hlkwa{while\ }\hlstd{}\hlsym{(}\hlstd{}\hlkwd{scanf}\hlstd{}\hlsym{(}\hlstd{}\hlstr{"\%u\ \%u"}\hlstd{}\hlsym{,\&}\hlstd{x}\hlsym{,\&}\hlstd{y}\hlsym{)==}\hlstd{}\hlnum{2}\hlstd{}\hlsym{)\ \{}\\
148 \hlline{49\ }\hlstd{}\hlstd{\ \ }\hlstd{cout\ }\hlsym{$<$$<$\ }\hlstd{x\ }\hlsym{$<$$<$}\hlstd{}\hlstr{"\ "}\hlstd{}\hlsym{$<$$<$\ }\hlstd{y\ }\hlsym{$<$$<$}\hlstd{}\hlstr{"\ "}\hlstd{\ }\hlsym{$<$$<$\ }\hlstd{}\hlkwd{resolver}\hlstd{}\hlsym{(}\hlstd{x}\hlsym{,\ }\hlstd{y}\hlsym{)\ $<$$<$\ }\hlstd{endl}\hlsym{;}\\
149 \hlline{50\ }\hlstd{\ }\hlsym{\}}\\
150 \hlline{51\ }\hlstd{\ }\hlkwa{return\ }\hlstd{}\hlnum{0}\hlstd{}\hlsym{;}\\
151 \hlline{52\ }\hlstd{}\hlsym{\}}\\
152 \hlline{53\ }\hlstd{}\\
153 \mbox{}
154 \normalfont
155 \shorthandon{"}